$(document).ready(function () {

    /// GLOBALS
    var map;
    var marker;
    var markersArrayPrivate = [];
    var markersArrayPublic = [];
    var markersArrayShared = [];
    var devicelist;

    $('#myonoffswitch-private').change(function () {
        var devices = $.parseJSON(devicelist);

        // Update Private - If is checked display, otherwise remove the markers for private devices
        if ($(this).is(':checked')) {
            var privateLength = devices.Private.length;

            var infowindow = new google.maps.InfoWindow();
            /// Parse Private Devices
            for (var i = 0; i < privateLength; i++) {

                var latlng_str = devices.Private[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];


                var privateLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: privateLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Private[i].Ip == null) ? "N/A" : devices.Private[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Private[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Private[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Private[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Private[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Private[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);

                markersArrayPrivate.push(marker);
            }
        } else {
            for (var i = 0; i < markersArrayPrivate.length; i++) {
                markersArrayPrivate[i].setMap(null);
            }
            markersArrayPrivate = [];
        }
    });

    $('#myonoffswitch-public').change(function () {
        var devices = $.parseJSON(devicelist);

        // Update Public - If is checked display, otherwise remove the markers for public devices
        if ($(this).is(':checked')) {
            var publicLength = devices.Public.length;

            var infowindow = new google.maps.InfoWindow();

            /// Parse Public Devices
            for (var i = 0; i < publicLength; i++) {

                var latlng_str = devices.Public[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];

                var publicLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: publicLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Public[i].Ip == null) ? "N/A" : devices.Public[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Public[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Public[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Public[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Public[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Public[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);

                markersArrayPublic.push(marker);
            }
        } else {
            for (var i = 0; i < markersArrayPublic.length; i++) {
                markersArrayPublic[i].setMap(null);
            }
            markersArrayPublic = [];
        }
    });

    $('#myonoffswitch-shared').change(function () {
        var devices = $.parseJSON(devicelist);

        // Update Shared - If is checked display, otherwise remove the markers for shared devices
        if ($(this).is(':checked')) {
            var sharedLength = devices.Shared.length;

            var infowindow = new google.maps.InfoWindow();

            /// Parse Shared Devices
            for (var i = 0; i < sharedLength; i++) {


                var latlng_str = devices.Shared[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];


                var sharedLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: sharedLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Shared[i].Ip == null) ? "N/A" : devices.Shared[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Shared[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Shared[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Shared[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Shared[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Shared[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);

                markersArrayShared.push(marker);
            }
        } else {
            for (var i = 0; i < markersArrayShared.length; i++) {
                markersArrayShared[i].setMap(null);
            }
            markersArrayShared = [];
        }
    });


    function initialize() {
        var myLatlng = new google.maps.LatLng(51.524362, -0.134475);
        var mapOptions = {
            zoom: 2,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        devicelist = loadAllDevices();


        /// If Devices exist for the logged in User
        if (devicelist != "401") {

            var devices = $.parseJSON(devicelist);
            console.log(devices);
            var privateLength = devices.Private.length;
            var publicLength = devices.Public.length;
            var sharedLength = devices.Shared.length;

            var infowindow = new google.maps.InfoWindow();

            /// Parse Private Devices
            for (var i = 0; i < privateLength; i++) {

                var latlng_str = devices.Private[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];

                var privateLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: privateLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Private[i].Ip == null) ? "N/A" : devices.Private[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Private[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Private[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Private[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Private[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Private[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);
                markersArrayPrivate.push(marker);

            }


            /// Parse Public Devices
            for (var i = 0; i < publicLength; i++) {
                console.log("Public");
                console.log(devices.Public[i].Longlat);

                var latlng_str = devices.Public[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];

                var publicLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: publicLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Public[i].Ip == null) ? "N/A" : devices.Public[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Public[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Public[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Public[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Public[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Public[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);
                markersArrayPublic.push(marker);

            }

            /// Parse Shared Devices
            for (var i = 0; i < sharedLength; i++) {
                console.log("Shared");
                console.log(devices.Shared[i].Longlat);

                var latlng_str = devices.Shared[i].Longlat;
                var latlng_tokens = latlng_str.split(",");
                var lat = latlng_tokens[0];
                var lng = latlng_tokens[1];

                var sharedLatLng = new google.maps.LatLng(lat, lng);

                marker = new google.maps.Marker({
                    position: sharedLatLng,
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                });

                /// Format IP Address
                var deviceip = ((devices.Shared[i].Ip == null) ? "N/A" : devices.Shared[i].Ip);

                var devContentHTML = "<table class='gridtable'>";
                devContentHTML += "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "ID" + "</td>" +
                       "<td>" + devices.Shared[i].Id + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Name" + "</td>" +
                       "<td>" + devices.Shared[i].Name + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Description" + "</td>" +
                       "<td>" + devices.Shared[i].Description + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Ip Address" + "</td>" +
                       "<td>" + deviceip + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Location" + "</td>" +
                       "<td>" + devices.Shared[i].Location + "</td>" +
                       "</tr>" +
                       "<tr class='solid-blue-2 light-text tr-row'>" +
                       "<td>" + "Coordinates" + "</td>" +
                       "<td>" + devices.Shared[i].Longlat + "</td>" +
                       "</tr>";
                devContentHTML += "</table>";


                makeInfoWindowEvent(map, infowindow, devContentHTML, marker);
                markersArrayShared.push(marker);
            }
        }
    }

    function makeInfoWindowEvent(map, infowindow, contentString, marker) {
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(contentString);
            infowindow.open(map, marker);
        });
    }

    if ($('#nav-subtab-3c').is(':checked')) {
        google.maps.event.addDomListener(window, 'load', initialize);
    }

    /// Hide all message info
    $('.nav-subtab-ctrl').click(function () {
        $('.submitResults').hide();
    });


    function loadAllDevices() {
        var devices = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/publicdevices/" + getUserID(),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var obj = jQuery.parseJSON(devices);

        if (obj.ErrorDetail == "Invalid UserIdBad Request") {
            return "401"; // Invalid UserID
        } else {
            return devices;
        }
    }


    function getUserID() {
        var userID = $.ajax({
            type: 'GET',
            url: "scripts/GetSessions.aspx",
            data: { "UserId": "true" },
            dataType: 'html',
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        return userID;
    }

    function pusherConfiguration() {
        var pusherConfiguration = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/subscribe?sensorid=" + $('#liveSensorName').val() + "&userid=" + getUserID(),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;
        return pusherConfiguration;
    }
});

